<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable @clear="getUserList" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="switchChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              @click="changeEditState(scope.row.id)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              @click="removeUser(scope.row.id) "
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                @click="showSetRole(scope.row)"
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
        <!-- 主题内容 -->
        <el-form
          :model="addRuleForm"
          :rules="addRules"
          ref="addRuleFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addRuleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addRuleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addRuleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addRuleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <!-- 主体信息 -->
        <el-form
          :model="editRuleForm"
          :rules="editRules"
          ref="editRuleFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editRuleForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editRuleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editRuleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog 
      title="分配角色" 
      :visible.sync="setRoleDialogVisible" 
      width="50%" 
      @close="setRoleDialogClosed">
        <div>
          <p>当前的用户:{{users.username}}</p>
          <p>当前的角色:{{users.role_name}}</p>
          <div>
            <el-select v-model="selectVelue" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setUserRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱验证规则
    const yzEmail = (rule, val, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(val)) {
        return cb();
      }
      return cb(new Error("请输入正确的邮箱"));
    };
    // 手机号验证规则
    const yzMobile = (rule, val, cb) => {
      const regMobile = /^1[3456789]\d{9}$/;
      if (!regMobile.test(val)) {
        return cb(new Error("请输入正确的手机号"));
      }
      return cb();
    };

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userlist: [],
      total: 0,
      // 当前分配角色的用户存储对象
      users: [],
      //所有角色列表的存储对象
      rolesList: [],
      // 控制添加用户的隐藏显示
      dialogVisible: false,
      // 控制编剧用户的隐藏显示
      editDialogVisible: false,
      //分配角色对话框的显示和隐藏
      setRoleDialogVisible: false,
      // 添加用户表单存储对象
      addRuleForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 修改用户表单存储对象
      editRuleForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加用户表单的校验规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入活动邮箱", trigger: "blur" },
          { validator: yzEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: yzMobile,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ]
      },
      //修改用户表单的校验规则
      editRules: {
        email: [
          { required: true, message: "请输入活动邮箱", trigger: "blur" },
          { validator: yzEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: yzMobile,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ]
      },
      // 存储角色选择下拉菜单中选中的值
      selectVelue:''
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败！");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表信息失败");
      this.rolesList = res.data;
    },
    // 用户改变数据显示条数时触发
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getUserList();
    },
    // 用户点击切换当前页时触发
    handleCurrentChange(newpage) {
      this.queryInfo.pagenum = newpage;
      this.getUserList();
    },
    // 用户状态发生变化时触发
    async switchChange(row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      );
      if (res.meta.status !== 200) return this.$message.error("修改失败");
      this.$message.success("修改成功");
    },
    // 关闭添加用户对话框
    addDialogClosed() {
      // 通过ref获取form表单数据，调用resetFields重置表单
      this.$refs.addRuleFormRef.resetFields();
    },
    // 添加用户
    addUser() {
      // 先校验表单是否填写完整
      // 如果填写完整，可以发送请求完成添加
      // 如果填写不完整，不可以发送，给一个提示
      this.$refs.addRuleFormRef.validate(async flag => {
        if (!flag) return this.$message.error("请将表单完善");
        const { data: res } = await this.$http.post("users", this.addRuleForm);
        console.log(res);

        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success("添加成功");
        this.dialogVisible = false;
        this.getUserList();
      });
    },

    // 显示编辑用户对话框
    async changeEditState(id) {
      const { data: res } = await this.$http.get(`users/${id}`);

      if (res.meta.status != 200)
        return this.$message.error("获取用户信息失败");
      this.editRuleForm = res.data;

      this.editDialogVisible = true;
    },
    editDialogClosed() {
      // 通过ref获取form表单数据，调用resetFields重置表单
      this.$refs.editRuleFormRef.resetFields();
    },
    // 修改用户
    editUser() {
      this.$refs.editRuleFormRef.validate(async flag => {
        //如果表单未完善 提示用户完善
        if (!flag) return this.$message.error("请完善表单！");
        //如果表单已经完善 发送修改用户请求\
        const { data: res } = await this.$http.put(
          `users/${this.editRuleForm.id}`,
          {
            email: this.editRuleForm.email,
            mobile: this.editRuleForm.mobile
          }
        );
        // 判断是否修改成功
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        // 如果修改成功 提示更新成功 关闭对话框 重新渲染数据
        this.$message.success("更新用户信息成功！");
        this.editDialogVisible = false;
        this.getUserList();
      });
    },
    // 删除用户
    removeUser(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          // 发起删除请求
          const { data: res } = await this.$http.delete("users/" + id);
          // 如果删除失败
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          //删除成功
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 显示分配角色对话框
    showSetRole(row) {
      this.users = row;
      this.getRolesList();
      this.setRoleDialogVisible = true;
    },
    // 分配角色给用户
    async setUserRole(){
      // 判断用户是否选择了新角色
      if(this.selectVelue === '') return this.$message.error("请选择要分配的新角色");
      // 发送请求
      const {data:res} = await this.$http.put(`users/${this.users.id}/${this.selectVelue}`);
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // 关闭对话框
      this.setRoleDialogVisible = false;
      // 重渲染数据
      this.getUserList();
      // 提示用户修改成功
      this.$message.success("修改角色成功");
    },
    // 设置角色对话框关闭事件
    setRoleDialogClosed(){
      this.selectVelue = '';
    }
  }
};
</script>

<style lang="less" scoped>
</style>
